package code.c13;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/12/2 14:22
 * @package code.c13
 * @description 消费者，生产者问题 - 仓库
 */

public class WareHouse {
    private int num;// 当前仓库的产品数
    private final int CAPACITY = 40;// 初始的仓库容量

    public WareHouse(int num) {
        if (num < CAPACITY){
            this.num = num;
        }else {
            System.out.println("超出仓库容量");
        }
    }

    /**
     * 生产
     */
    synchronized void produce(int value)  {
        // 生产的数量，小于库存量,就生产,否则就等待
        while (value < CAPACITY - num) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        num += value;
        System.out.println("生产者生产" + value + "件商品后仓库还剩:" + num + "件商品");
        notify();// 唤醒线程
    }

    /**
     * 消费
     */
    synchronized void consume(int value)  {
        while (value > num) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num -= value;
        System.out.println("消费者消费" + value + "件商品后仓库还剩:" + num + "件商品");
        notify();
    }
}
